<template>
  <Layout style="background: white;padding:10px;height: 100%">
    <Header style="padding: 10px">
      <div style="display: inline-block;width: 140px;padding-right: 10px">
        <Select :datas="servers" v-model="currentServer" :deletable="false" @change="loadPath('/')"></Select>
      </div>
      <Breadcrumb :datas="paths" @click="toPath" style="display:inline;" selfControl></Breadcrumb>
      <Button icon="icon-file" text style="float: right;padding:8px 5px;" @click="newFile">新建文件</Button>
      <Button icon="icon-folder" text style="float: right;padding:8px 5px;" @click="newDir">新建目录</Button>
      <FileInput accept="*" @change="upload" multiple>
        <Button icon="h-icon-outbox" text style="float: right;padding:8px 5px;">上传</Button>
      </FileInput>
    </Header>
    <Content style="flex:1">
      <Table :datas="files" @trdblclick="openFile">
        <TableItem title="序号" prop="$serial" :width="50"></TableItem>
        <TableItem title="文件">
          <template slot-scope="{data}">
            <svg class="icon" aria-hidden="true">
              <use :xlink:href="data.type|toType"></use>
            </svg>
            {{ data.name }}
          </template>
        </TableItem>
        <TableItem align="center" title="大小">
          <template slot-scope="{data}">
            <div v-if="data.type!='dir'">{{ data.size|bytes }}</div>
            <div v-else>--</div>
          </template>
        </TableItem>
        <TableItem title="修改日期" prop="lastModify" :format="dateFormat"></TableItem>
        <TableItem :width="170">
          <template slot-scope="{data}">
            <Poptip content="确认删除?" @confirm="deleteFile(data.name)">
              <i class="h-icon-trash" style="cursor: pointer">删除</i>
            </Poptip>
            <div class="h-tooltip-show" @click="rename(data.name)">
              <i class="icon-reply" style="cursor: pointer">重命名</i>
            </div>
            <Poptip content="确认导出?" @confirm="download(data.name)">
              <i class="h-icon-inbox" style="cursor: pointer">导出</i>
            </Poptip>
            &nbsp;<i v-if="data.type=='zip'" class="h-icon-inbox" style="cursor: pointer">解压</i>
          </template>
        </TableItem>
        <div slot="empty">暂时无数据</div>
      </Table>
    </Content>
    <Modal v-model="edit" :hasCloseIcon="true" :hasDivider="true" :closeOnMask="false" :fullScreen="true">
      <div slot="header">编辑</div>
      <MonacoEditor style="height: 100%" :language="language" :value="source" @save="saveFile"
                    ref="editor"></MonacoEditor>
      <div slot="footer">
        <button class="h-btn" @click="edit=false">取消</button>
        <button class="h-btn h-btn-primary" @click="doSave">保存</button>
      </div>
    </Modal>
  </Layout>
</template>
<script>
import {ajax,format} from 'framework'

let Vue = require('vue');

Vue.filter('bytes', function renderSize(value) {
  if (null == value || value == '') {
    return "0 B";
  }
  var unitArr = new Array("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB");
  var index = 0;
  var srcsize = parseFloat(value);
  index = Math.floor(Math.log(srcsize) / Math.log(1024));
  var size = srcsize / Math.pow(1024, index);
  size = size.toFixed(0);//保留的小数位数
  return size + unitArr[index];
})
let types = ["dxf", "vcs", "elf", "vdx", "eml", "vcf", "el", "vmdk", "enc", "vob", "editorconfig", "vox", "eot", "vsd", "epub", "vss", "eps", "vst", "eslintignore", "vsx", "fax", "vdi", "flac", "vscodeignore", "fla", "vtx", "exe", "wav", "f4v", "wbk", "fb2", "webinfo", "gadget", "webp", "fon", "webm", "flv", "wma", "gem", "war", "gif", "wmf", "fnt", "wmv", "gdp", "woff", "gitignore", "wpd", "gpl", "woff2", "gitattributes", "wps", "gpg", "wsf", "gz", "xaml", "gradle", "xcf", "go", "xfl", "h", "xlb", "heic", "xlc", "hs", "xls", "handlebars", "xlm", "hsl", "xlsb", "hbs", "xlsm", "htm", "xlsx", "hlp", "xlt", "ibooks", "xltx", "html", "xltm", "icma", "xml", "icns", "xps", "ico", "xrb", "icml", "xpi", "idx", "xsl", "image", "xspf", "iff", "xz", "ics", "yaml", "ifo", "yml", "img", "z", "in", "zip", "iml", "3ga", "inc", "3g2", "inf", "zsh", "inv", "3gp", "indd", "7z", "info", "aa", "ini", "aac", "iso", "ac", "jpe", "accdb", "jar", "accdt", "java", "ace", "j2", "adn", "jpeg", "aif", "jpg", "aifc", "json", "aiff", "jsp", "ait", "key", "amr", "kit", "xsd", "ksh", "ani", "kf8", "app", "kmk", "apk", "js", "asc", "jsx", "asax", "kts", "applescript", "lex", "ai", "kt", "ascx", "licx", "asf", "lisp", "ash", "kup", "ashx", "less", "asm", "list", "asmx", "lock", "asp", "lit", "aspx", "lua", "asx", "log", "au", "lnk", "avi", "m3u8", "aup", "m4r", "bak", "m3u", "aze", "m2v", "axd", "m4a", "bash", "m4", "bat", "m", "bin", "master", "blank", "mdb", "bmp", "md", "bowerrc", "map", "bpg", "mdf", "browser", "m4v", "bz2", "mc", "bzempty", "me", "c", "mid", "cab", "midi", "cad", "mm", "caf", "mi", "mkv", "mk", "mng", "mo", "mp3", "mov", "mp2", "mod", "mp4", "mpd", "mpe", "mobi", "mpg", "mpt", "mpga", "mpeg", "mpp", "mpa", "msi", "msu", "msg", "nes", "nfo", "nix", "npmignore", "nef", "odb", "odt", "ogg", "ogv", "ods", "ocx", "ott", "one", "ost", "otf", "ova", "p7b", "part", "p12", "pages", "partial", "pbix", "ovf", "pem", "pcd", "pdf", "pfx", "pgp", "pdb", "ph", "pid", "pkg", "php", "phar", "po", "png", "plist", "pl", "pom", "pm", "pps", "potx", "ppk", "pot", "ppt", "ppsx", "pptx", "ps", "prop", "psp", "psd", "pst", "pptm", "ps1", "pub", "pyc", "ram", "rb", "rdl", "raw", "rdf", "reg", "ra", "rar", "qt", "py", "rpt", "rm", "retry", "cd", "rpm", "cal", "resx", "cfg", "rom", "cer", "rub", "cgi", "ru", "cfm", "save", "cfml", "sass", "cdda", "rst", "cmd", "sesx", "code-workspace", "rss", "codekit3", "scss", "codekit", "sed", "class", "sit", "com", "rsa", "coffeelintignore", "rtf", "chm", "sitemap", "config", "sldm", "conf", "sdf", "compile", "sketch", "cr2", "skin", "cpp", "sln", "cptx", "sldx", "crdownload", "sh", "crypt", "sol", "crt", "srt", "cson", "sqlite", "csh", "sql", "cs", "step", "csv", "sphinx", "css", "stl", "cur", "svg", "csproj", "sub", "cue", "swf", "coffee", "tar", "db", "tex", "dat", "sys", "data", "tax", "dbf", "tfignore", "deb", "swp", "default", "tga", "dist", "tcsh", "dng", "tgz", "dgn", "swd", "dll", "tif", "diz", "tiff", "dmg", "tmx", "docm", "tmp", "doc", "ts", "docb", "torrent", "docx", "tsx", "dotm", "ttf", "dot", "tsv", "dotx", "twig", "download", "tpl", "dpj", "udf", "ds_store", "txt", "dsn", "vb", "dst", "vbproj", "dtd", "vbs", "dwg", "vcd", "dir"];
Vue.filter('toType', function (value) {
  if (types.indexOf(value) > -1) {
    return "#icon-" + value;
  } else {
    return "#icon-unkown"
  }
})
export default {
  data() {
    return {
      paths: [{
        icon: 'h-icon-home',
        route: "/"
      }],
      files: [],
      current: "",
      edit: false,
      source: '',
      language: '',
      editFile: '',
      currentServer:'',
      servers:[]
    }
  },
  mounted() {
    ajax.get("server/list_servers").then(r => {
      this.servers = r.data
      if(r.data.length>0){
        this.currentServer=r.data[0]
      }
      this.loadPath("/")
    })
  },
  methods: {
    dateFormat: format("yyyy-MM-dd hh:mm:ss"),
    loadPath(path) {
      if(!this.currentServer){
        this.files=[]
        return;
      }
      ajax.get("server/list_file", {serverName:this.currentServer,path: path}).then(r => {
        //set paths
        if (path == "" || path == "/") {
          this.current = "/";
          this.paths = [{
            icon: 'h-icon-home',
            route: "/"
          }];
        } else {
          let paths = path.replace(/(^\/)|(\/$)/, "").split("/");
          let temp = "/";
          let parr = [{
            icon: 'h-icon-home',
            route: "/"
          }];
          for (let i = 0; i < paths.length; i++) {
            let p = paths[i];
            if (p) {
              temp = temp + p + "/";
              parr.push({
                title: p,
                route: temp
              })
            }
          }
          if (!temp.endsWith("/")) {
            temp = temp + "/"
          }
          this.current = temp;
          this.paths = parr;
        }

        this.files = r.data;

      })
    },
    toPath(e) {
      if (e.route != this.current) {
        this.loadPath(e.route)
      }
    },
    openFile(file) {
      if (file.type == "dir") {
        this.loadPath(this.current + file.name)
        return;
      }
      if (["zip", "jar", "war", "rar", "exe", "db"].indexOf(file.type) > -1) {
        this.$Confirm("导出文件？").then((e) => {
          this.download(file.name)
        }).catch(c => {
        })
        return;
      }
      this.editFile = file.name;
      ajax.get("server/load_file", {serverName:this.currentServer,path: this.current + file.name}).then(f => {
        this.source = f.data;
        if (file.name == 'nginx.conf' || file.name == 'nginx.conf.tpl') {
          this.language = 'nginx';
        } else {
          this.language = file.type;
        }

        this.edit = true;
      })

    },
    doSave() {
      this.$refs.editor.save()
    },
    saveFile(value) {
      ajax.post("server/save_file",{serverName:this.currentServer,path:this.current+this.editFile,file:value}).then(r=>{
        this.$Message("已保存")
      })
    },
    download(file) {
      ajax.download("server/export_file?serverName="+this.currentServer+"&path=" + this.current + file)
      // ajax.get("file/export",{path:this.current+file})
    },
    deleteFile(file) {
      ajax.post("server/remove_file", {serverName:this.currentServer,path: this.current + file}).then(r => {
        this.loadPath(this.current)
      })
    },
    upload(file) {
      if (file.length == 0) {
        return;
      }
      ajax.upload("server/upload_file", {serverName:this.currentServer,path: this.current, file: file[0]}).then(r => {
        this.loadPath(this.current)
      }).catch(e => {
        this.$Message("上传失败")
      })
    },
    newFile(){
      this.$Prompt("请输入文件名").then(r=>{
        ajax.upload("server/new_file", {serverName:this.currentServer,path: this.current, file:r }).then(r => {
          this.loadPath(this.current)
        }).catch(e => {
          this.$Message("新建失败")
        })
      })
    },
    newDir(){
      this.$Prompt("请输入文夹件名").then(r=> {
        ajax.upload("server/new_dir", {serverName: this.currentServer, path: this.current, file: r}).then(r => {
          this.loadPath(this.current)
        }).catch(e => {
          this.$Message("新建失败")
        })
      })
    },
    rename(file){
      this.$Prompt("请输新的名称",file).then(r=> {
        ajax.post("server/rename", {serverName:this.currentServer,path: this.current + file,newName:r}).then(r => {
          this.loadPath(this.current)
        })
      })
    }
  }
}
</script>
